use image::io::Reader as ImageReader;
use log::{error, info};
use std::path::Path;
use tao::window::Icon;
// 修复语法错误，添加返回类型 `Option<&'static str>`
// 修复返回类型为 `Option<&'static str>` 以匹配后续代码的返回值类型
pub fn get_content_type(file_path: &str) -> &'static str {
    Path::new(&file_path)
        .extension()
        .and_then(|e| e.to_str())
        .map(|ext| match ext.to_lowercase().as_str() {
            "js" => "application/javascript",
            "mjs" => "application/javascript",
            "html" => "text/html",
            "css" => "text/css",
            // 文本类型
            "htm" => "text/html",
            "json" => "application/json",
            "txt" => "text/plain",
            "xml" => "application/xml",

            // 图片类型
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "ico" => "image/x-icon",

            // 字体类型
            "woff" => "font/woff",
            "woff2" => "font/woff2",
            "ttf" => "font/ttf",

            // 二进制数据
            "pdf" => "application/pdf",
            "zip" => "application/zip",
            "gz" => "application/gzip",

            // 多媒体
            "mp3" => "audio/mpeg",
            "mp4" => "video/mp4",
            "webm" => "video/webm",
            _ => "text/plain",
        })
        .unwrap_or("text/plain")
}

pub fn load_icon_from_png(path: &str) -> Option<Icon> {
    // 使用 image 库加载 PNG 文件
    let img = match ImageReader::open(path) {
        Ok(reader) => reader.decode().ok()?,
        Err(e) => {
            error!("Failed to open PNG file '{}': {}", path, e);
            return None;
        }
    };

    // 转换为 RGBA 格式
    let rgba = img.to_rgba8();

    // 创建 tao::window::Icon
    match Icon::from_rgba(rgba.to_vec(), rgba.width(), rgba.height()) {
        Ok(icon) => {
            info!(
                "Icon loaded successfully: {}x{}",
                rgba.width(),
                rgba.height()
            );
            Some(icon)
        }
        Err(e) => {
            error!("Failed to create icon: {}", e);
            None
        }
    }
}
